﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace PocketCargo
{
    static class Program
    {
        private const int SW_HIDE = 0;//API参数表示隐藏窗口
        private const int SW_SHOW = 5;//API参数表示用当前的大小和位置显示窗口
        [DllImportAttribute("coredll")]
        static extern int FindWindow(string ClassName, string WindowName);
        [DllImport("coredll")]
        static extern int ShowWindow(int handle, int cmdShow);

        [System.Runtime.InteropServices.DllImport("Auto3G", SetLastError = true)]
        static extern UInt32 Drop3G();
        [System.Runtime.InteropServices.DllImport("Auto3G", SetLastError = true)]
        static extern UInt32 Get3GStatus();
        [System.Runtime.InteropServices.DllImport("Auto3G", SetLastError = true)]
        static extern UInt32 Dial3G();

        [System.Runtime.InteropServices.DllImport("localmac", SetLastError = true)]
        static extern bool IsProgramInRun(String wszProgramName, ref System.IntPtr pHandle);

        [System.Runtime.InteropServices.DllImport("Coredll", SetLastError = true)]
        static extern bool CloseHandle(System.IntPtr hObject);


        static private void ShowTaskWindow()
        {
            int hWnd = FindWindow("HHTaskBar", null);
            ShowWindow(hWnd, SW_SHOW);
        }
        static private void HideTaskWindow()
        {
            int hWnd = FindWindow("HHTaskBar", null);
            ShowWindow(hWnd, SW_HIDE);
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [MTAThread]
        static void Main()
        {
            UInt32 st;
            Drop3G();
            HideTaskWindow();

            // 如果多次启动，程序直接退出
            System.IntPtr runHandle = new System.IntPtr();
            bool fRun = IsProgramInRun("PocketCargo_In_Run", ref runHandle);
            if (fRun)
            {
                return;
            }

            Application.Run(new MainForm());

            // 关闭程序启动标识
            CloseHandle(runHandle);

            //ShowTaskWindow();
            // 添加断开连接
            st = Get3GStatus();
            if (st == 1)
            {
                // 断开连接
                Drop3G();
            }
        }
    }
}